/**
 * 
 */
package neptune.manager.validator.rules.topology;

import neptune.manager.model.topology.Link;
import neptune.manager.model.topology.NetworkInterface;
import neptune.manager.model.topology.Node;
import neptune.manager.model.topology.Topology;
import neptune.manager.utils.Logger.MessageType;
import neptune.manager.validator.ValidatorResult;
import neptune.manager.validator.ValidatorRule;
import neptune.manager.validator.Validator.Status;

/**
 * @author Roberto Bifulco [RobertoBifulco.it] [info@robertoBifulco.it]
 * 
 */
public class LinkEndPointCoerenceRule extends ValidatorRule<Topology> {

	@Override
	public String getName() {
		return "LinkEndPointCoerenceRule";
	}

	@Override
	protected ValidatorResult validationAlgorithm(Topology toValidate,
			ValidatorResult result) {

		result.getLog().addMessage("Veryfing coerence in links'end-point",
				MessageType.NORMAL);

		for (Link link : toValidate.getLinks()) {
			result.getLog().addMessage("Veryfing link: '" + link.getId() + "'",
					MessageType.NORMAL);

			if (link.getSource() != null) {
				// Verifica l'esistanza del nodo
				String sourceNode = link.getSource().getNodeId();
				Node source = toValidate.searchNodeIntoTopology(sourceNode);

				if (source == null) {
					result.setStatus(Status.ERROR);
					result.getLog().addMessage(
							"Source node '" + sourceNode + "' not found.",
							MessageType.ERROR);
				} else {
					// Verifica l'esistenza dell'interfaccia
					String sourceInterface = link.getSource().getInterfaceId();
					NetworkInterface sourceIf = source
							.getInterfaceByName(sourceInterface);

					if (sourceIf == null) {
						result.setStatus(Status.ERROR);
						result.getLog().addMessage(
								"Source interface '" + sourceInterface
										+ "' not found in source node '"
										+ sourceNode + "'", MessageType.ERROR);
					}
				}
			}
			if (link.getDestination() != null) {
				String destinationNode = link.getDestination().getNodeId();

				Node destination = toValidate
						.searchNodeIntoTopology(destinationNode);

				if (destination == null) {
					result.setStatus(Status.ERROR);
					result.getLog().addMessage(
							"Destination node '" + destinationNode
									+ "' not found.", MessageType.ERROR);
				} else {
					// Verifica l'esistenza dell'interfaccia
					String destinationInterface = link.getDestination().getInterfaceId();
					NetworkInterface destinationIf = destination
							.getInterfaceByName(destinationInterface);

					if (destinationIf == null) {
						result.setStatus(Status.ERROR);
						result.getLog().addMessage(
								"Source interface '" + destinationInterface
										+ "' not found in source node '"
										+ destinationNode + "'", MessageType.ERROR);
					}
				}
			}

		}

		return result;
	}

}
